
package it.csttech.date;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.Locale;

import javax.ws.rs.WebApplicationException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * This class is a module of the object mapper whose purpose is to marshal a
 * java float object into a JSON string according to the request locale
 * 
 * @author marcello.felappi
 * @author marco.dalena
 */
public class FloatJsonSerializer extends JsonSerializer<Float> {

	/**
	 * Locale of the request
	 */
	private Locale locale;

	/**
	 * Empty constructor
	 */
	public FloatJsonSerializer() {

	}

	/**
	 * Constructor, accepts locale as input
	 * 
	 * @param locale
	 *            - locale of the request
	 */
	public FloatJsonSerializer(Locale locale) {

		this.locale = locale;
	}

	/**
	 * This method is used to marshal a java java float object "f" into a JSON
	 * string according to the request locale
	 * 
	 * @param Float
	 *            f - input float number
	 * @param JsonGenerator
	 *            jgen - json generator that marshals the data
	 * @param SerializerProvider
	 *            sp - provider that register the serializer
	 * @throws IOException
	 *             - I/O exception
	 * @throws JsonProcessingException
	 *             - exception thrown during the json processing
	 * @throws WebApplicationException
	 *             - excpetion thrown if the locale is not supported by the
	 *             server
	 */
	@Override
	public void serialize(Float f, JsonGenerator jgen, SerializerProvider sp)
		throws IOException, JsonProcessingException {

		String fFormat = null;
		try {
			fFormat = NumberFormat.getInstance(locale).format(f);
		}
		catch (Exception e) {
			throw new WebApplicationException(
				Messages.getString("ErrorCode.localeNotSupported"));
		}
		jgen.writeString(fFormat);

	}

	public Locale getLocale() {

		return locale;
	}

	public void setLocale(Locale locale) {

		this.locale = locale;
	}
}
